package com.agent.service.mail.impl;

import com.agent.entity.RepaireInfo;
import com.agent.entity.User;
import com.agent.service.IRepaireInfoService;
import com.agent.service.UserService;
import com.agent.spring.websocket.SpringWebSocketHandler;
import com.agent.util.Constants;
import com.weixin.util.WXUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.TextMessage;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Created by hg on 2019/1/31.
 */
@Service("repaireInfoBiz")
@Slf4j
public class RepaireInfoBiz {
    @Autowired
    IRepaireInfoService service;
    @Resource(name = "userServiceImpl")
    UserService userService;

    @Bean
    public SpringWebSocketHandler infoHandler() {
        return new SpringWebSocketHandler();
    }

    @Resource(name="transactionManager")
    PlatformTransactionManager platformTransactionManager;

    public TransactionTemplate getTransactionTemplate(PlatformTransactionManager platformTransactionManager){
        return new TransactionTemplate(platformTransactionManager);
    }


    public boolean insertByEmail(String content,String fromEmail) {
        // 没有内容也提醒
        /*if(StringUtils.isEmpty(content)){
            return false;
        }*/
//        RepaireInfo repaireInfo = parseContent(content);
        RepaireInfo repaireInfo = new RepaireInfo();
        repaireInfo.setDescription(content);
        User in = new User();
//        in.setRoleId(null);
        in.setEmail(fromEmail);
        getTransactionTemplate(platformTransactionManager).execute(transactionStatus ->{
            try{
                List<User> userList = userService.findUser(in);
                if(userList ==null || userList.size()==0){
                    log.error("该用户邮箱未注册:{}，请核实！",fromEmail);
                    return false;
                }
                User user = userList.get(0);
                repaireInfo.setCreateTime(new Date());
                repaireInfo.setCallerDeptId(user.getDeptId());
                repaireInfo.setCreator(user.getUserName());
                repaireInfo.setCreatorName(user.getDisplayName());
                repaireInfo.setWorkOrderId(WXUtil.gengertorId());
                repaireInfo.setCreatorPhone(user.getTelphone());
                repaireInfo.setSource("2");// 邮件报修
                repaireInfo.setStatus("07");
                service.insert(repaireInfo);

                List<User> list = userService.findByRole();
                if(!CollectionUtils.isEmpty(list)){
                    StringBuffer sb = new StringBuffer();
                    for (User u : list) {
                        sb.append(u.getUserName());
                        sb.append("|");
                    }
                    String toUser = sb.substring(0,sb.length()-1);
                    StringBuffer socketMsg = new StringBuffer();
                    socketMsg.append("email报修提醒：【姓名："+repaireInfo.getCreatorName()+"<br/>备注："+repaireInfo.getDescription()+"】" +
                            "<br/>请点击<a href=javascript:emailInsert("+repaireInfo.getId()+","+JSONObject.fromObject(repaireInfo)+")>处理</a>");
                    infoHandler().sendMessageToUsersByName(toUser, new TextMessage(socketMsg));
                }
            }catch (Exception e){
                transactionStatus.setRollbackOnly();
            }
            return true;
        });
        return true;
    }

    public static void main(String[] args) {
        String content = "报修人电话：15021422141\n" +
                "报修地址：徐家汇\n" +
                "报修类型：电脑\n" +
                "描述：我的电脑坏了";
        RepaireInfoBiz impl = new RepaireInfoBiz();

        System.out.println(impl.parseContent(content));
    }
    RepaireInfo parseContent(String content){
        RepaireInfo repaireInfo = new RepaireInfo();
        String[] strs = content.split("\n");
        for(String line:strs){
            String[] lineContent= line.split("：");
            if(lineContent.length!=2){
                throw new IllegalArgumentException("line content is error, line content  is "
                        + CollectionUtils.arrayToList(lineContent).toString());
            }
            switch (lineContent[0]){
                case "报修人电话": repaireInfo.setCreatorPhone(lineContent[1]); break;
                case "报修地址": repaireInfo.setAddress(Constants.getAddressByValue(lineContent[1])); break;
                case "报修类型": repaireInfo.setMachineType(Constants.getMachineTypeByValue(lineContent[1])); break;
                case "描述": repaireInfo.setDescription(lineContent[1]); break;
                default:throw  new IllegalArgumentException("line content style is error");
            }
        }
        repaireInfo.setSource("2");
        return repaireInfo;
    }
}
